/****************
 *@description: 采购退货列表  procurement/pruchaseReturn/index
 *@author: Xhd
 *@date: 2023-07-21 11:31:33
 *@version: V1.0.0
*************************************************************************/

import React, { Component } from 'react';
import ThePagination from "@/components/ThePagination";
import { Tooltip } from "antd";
import { QuestionCircleOutlined } from "@ant-design/icons";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import TheQueryForm from '../../../components/TheQueryForm';
import TheTableExtend from '@/components/TheTableExtend'
import store from "@/store/store"
import _ from 'lodash';
import { getDateTime3 } from '@/utils/getDate'
import { exportSheetTable } from '@/utils/exportTable.js';
import { apiStockInLibraryPage, apiStockInLibraryDel, apiTSysDictionariesList, apiPrintStockInLibraryList } from '@/request/procurement/putIn.js'
export default class OutPut extends Component {
  constructor() {
    super()
    this.voucherFormRef = React.createRef()
    this.queryFormRef = React.createRef()
    this.state = {
      columns: [
        {
          title: "序号",
          dataIndex: "index",
          key: "index",
          render: (text, record, index) => {
            return ((this.state.pageData.pageNo - 1) * (this.state.pageData.pageSize) + (index + 1));
          }
        },
        {
          title: "入库单号",
          dataIndex: "code",
          key: "code",
        },
        {
          title: "对应单号",
          dataIndex: "otherCode",
          key: "otherCode",
          filterDropdown: true, // 自定义的列筛选功能，我们占位为信息提示Icon的位置
          filterIcon: () => {
            return (
              <Tooltip zIndex={999} placement="top" title={() => {
                return <div>
                  采购单生成入库单：采购单号<br />
                  商城退货生成入库单：商城退货单号<br />
                  门店退货生成入库单：门店订单号<br />
                  收银台退货生成入库单：门店订单号<br />
                  收银台取消订单：门店订单号<br />
                  调拨入库单：出库单号
                </div>
              }}  >
                <QuestionCircleOutlined />
              </Tooltip>
            );
          },
        },
        {
          title: "入库日期",
          dataIndex: "finishTime",
          key: "finishTime",
        },
        {
          title: "入库类型",
          dataIndex: "dataType",
          key: "dataType",

          render: (text, render) => {
            return this.state.data.map((item) => {
              if (render.dataType == Number(item.value)) {
                return item.name
              }
            })
          }
        },
        {
          title: "入库仓库",
          dataIndex: "libraryName",
          key: "libraryName",
        },
        {
          title: "供应商",
          dataIndex: "supplierName",
          key: "supplierName",
        },
        {
          title: "凭证编码",
          dataIndex: "voucherCode",
          key: "voucherCode"
        },
        {
          title: "状态",
          dataIndex: "status",
          key: "status",
          render: (text) => {
            if (text == 0) {
              return <div style={{ color: "red" }} >未完成</div>
            } else {
              return '已完成'
            }
          }
        },
        {
          title: "登记人",
          dataIndex: "memberName",
          key: "memberName",

        },
        {
          title: "登记日期",
          dataIndex: "createTime",
          key: "createTime",
          defaultChange: true
        }, {
          title: "操作",
          dataIndex: "serviceShowFile",
          key: "serviceShowFile",
          fixed: 'right',
          render: (text, render) => {
            return <div>
              <TheButton haspermi={['storage:putIn:view']} onClick={() => this.props.history.push('/procurement/putIn/details/' + render.id)}>查看详情</TheButton>
            </div>
          }
        },
      ],
      newColumns: [],
      form_show: true,
      searchOption: [
        { field: 'code', label: '入库单号', placeholder: '请输入入库单号', required: false, rules: [], type: 'Input', defaultValue: '' },
        { field: 'otherCode', label: '对应单号', placeholder: '请输入对应单号', required: false, rules: [], type: 'Input', defaultValue: '' },
        { field: 'status', label: '状态', placeholder: '请选择状态', required: false, rules: [], type: 'Select', options: [{ label: '未完成', value: '0', }, { label: '已完成', value: '1' }], defaultValue: '' },
        { field: 'time', label: '入库日期', placeholder: '请选择', required: false, rules: [], type: 'RangePicker' },
        { field: 'supplierName', label: '供应商', placeholder: '请选择供应商', required: false, rules: [], type: 'Input', options: [], defaultValue: '' },
      ],
      queryForm: {},
      dataSource: [],
      pageData: {
        pageNo: 1,
        pageSize: 10
      },
      total: 0,
      code: '',
      sumCount: "",
      sumPrice: "",
      data: '',
      selectedKeys: { 1: [] },
    }
  }

  async componentDidMount() {
    let res = await apiTSysDictionariesList({ type: 'in_library_type', level: 2 })
    this.setState({
      data: res.data
    })
    this.onColumnsFilter(this.state.columns)
    let searchParams = store.getState().searchValue
    let { pageNo, pageSize, queryForm, pathName, code } = searchParams
    if (searchParams && pageNo && pathName == 'purchaseReturn') {
      // let { pageNo, pageSize, code } = searchParams
      this.setState({
        code,
        pageData: {
          pageNo: pageNo, pageSize: pageSize
        }
      }, () => {
        this.queryFormRef.onSetDefault({ ...queryForm })
        this.getData()
      })
    } else {
      this.getData()
    }
  }

  getData(values) {
    let { pageNo, pageSize } = this.state.pageData
    if (values && !_.isEmpty(values.time)) {
      values.finishTimeStart = getDateTime3(values.time[0]) + ' 00:00:00'
      values.finishTimeEnd = getDateTime3(values.time[1]) + ' 23:59:59'
    }
    this.setState({
      queryForm: values === undefined ? this.state.queryForm : { ...values }
    }, async () => {
      const params = {
        pageNo, pageSize, queryForm: this.state.queryForm
      }
      store.dispatch({
        type: 'SaveSearchValues',
        data: {
          pathName: 'purchaseReturn',
          ...params
        }
      })
      await apiStockInLibraryPage({
        pageNo, pageSize, ...this.state.queryForm
      }).then(res => {
        if (res.code === 0 && res.data.sum !== null) {
          this.setState({
            dataSource: res.data.resultPage,
            total: res.totalCount,
            sumCount: res.data.sum.sumCount,
            sumPrice: res.data.sum.sumPrice / 100,
          })
        } else {
          this.setState({
            dataSource: res.data.resultPage,
            total: res.totalCount,
            sumCount: "0",
            sumPrice: "0",
          })
        }
      })
    })
  }

  del(row) {
    React.$confirm({
      title: "提示",
      type: 'warning',
      content: "确定是否删除？",
      onOk: async () => {
        let res = await apiStockInLibraryDel({ id: row.id })
        if (res.code === 0) {
          this.pageChange(1, 10)
          React.$message({
            type: 'success',
            content: res.codeMessage
          })
        } else {
          React.$message({
            type: 'warning',
            content: res.codeMessage
          })
        }
      }
    });
  }

  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo, pageSize
      }
    }, () => {
      this.getData()
    })
  }

  onReset() {
    this.setState({
      queryForm: {}
    }, () => {
      this.pageChange(1, 10)
    })
  }

  onTableRefresh() {
    this.getData()
  }

  onColumnsFilter(value) {
    this.setState({
      newColumns: value
    })
  }

  onFormSearch(values) {
    this.setState({
      pageData: { pageNo: 1, pageSize: 10 }
    }, () => {
      this.getData(values)
    })
  }

  onChange = (selectedRowKeys, selectedRows) => {
    let pageNo = this.state.pageData.pageNo
    let selectedKeys = { ...this.state.selectedKeys }
    selectedKeys[pageNo] = selectedRowKeys
    this.setState({
      selectedKeys
    })
  }

  toExport = async () => {
    const { queryForm } = this.state
    let ids = ""
    if (queryForm && !_.isEmpty(queryForm.time)) {
      queryForm.finishTimeStart = getDateTime3(queryForm.time[0])
      queryForm.finishTimeEnd = getDateTime3(queryForm.time[1])
    }
    Object.values(this.state.selectedKeys).forEach(value => {
      ids += value.toString() + ","
    })
    if (ids === ",") {
      ids = ""
    }
    await apiPrintStockInLibraryList({ ...queryForm, ids }).then(res => {
      if (res.code === 0 && res.data) {
        let th_arr = [
          {
            title: '入库单详情',
            prop: '',
            children: [
              {
                title: '序号',
                prop: 'index',
              },
              {
                title: '入库单号',
                prop: 'code',
              },
              {
                title: '商品名称',
                prop: 'goodsName',
              },
              {
                title: '物料名称',
                prop: 'materialName',
              },
              {
                title: '规格',
                prop: 'goodsSkuName',
              },
              {
                title: "物料ID",
                prop: "materialId",
              },
              {
                title: '入库前库存',
                prop: 'beforeCount',
                valueType: 'number'
              },
              {
                title: '入库数量',
                prop: 'count',
                valueType: 'number'
              },
              {
                title: '状态',
                prop: 'status'
              },
              {
                title: '操作时间',
                prop: 'createTime',
              },
              {
                title: '操作人',
                prop: 'memberName',
              }
            ]
          },
        ]
        let tb_arr = []
        res.data.forEach((item, index) => {
          item.printStockInLibraryDetailVos.forEach(item2 => {
            tb_arr.push({
              index: index + 1,
              code: item.code || '/',
              goodsName: item2.goodsName || '/',
              materialName: item2.materialName || '/',
              goodsSkuName: item2.goodsSkuName || '/',
              materialId: item2.materialId || '/',
              beforeCount: item2.beforeCount || '/',
              count: item2.count || '/',
              status: item.status === 0 ? '未处理' : '已处理',
              createTime: item.createTime || '/',
              memberName: item.memberName || '/',
            })
          })
        })
        const mergeProp = [
          'index',
          'code',
          'goodsName',
          'status',
          'createTime',
          'memberName',
        ]
        exportSheetTable({ fileName: '入库单详情', tH_data: th_arr, tB_data: tb_arr, isSheet: true, merge: true, mergeProp })
        this.setState({
          selectedKeys: { 1: [] }
        })
      }
    })
  }

  render() {
    let { columns, dataSource, pageData, total, form_show, searchOption, newColumns, sumCount, sumPrice, selectedKeys, visible, vouchercode } = this.state
    const rowSelection = {
      selectedRowKeys: selectedKeys[pageData.pageNo],
      onChange: this.onChange,
    }
    return (
      <div className="p-layout-box commodity-examine">
        <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
          onGetValues={(values) => this.onFormSearch(values)}
          onReset={(values) => this.onReset(values)}
        ></TheQueryForm>
        <TheTableExtend
          columns={columns}
          onFormTrigger={() => this.setState({ form_show: !this.state.form_show })}
          onTableRefresh={() => this.onTableRefresh()}
          onColumnsFilter={(value) => this.onColumnsFilter(value)}
        >
          <TheButton size="middle" onClick={() => this.toExport()} type="default">导出</TheButton>
        </TheTableExtend>

        <TheTable
          scroll={{ x: "max-content", y: '53vh' }}
          columns={newColumns}
          dataSource={dataSource}
          rowKey={record => record.id}
          rowSelection={rowSelection}
        />
        <ThePagination
          pageNo={pageData.pageNo}
          pageSize={pageData.pageSize}
          total={total}
          pageChange={this.pageChange}
        />
      </div>
    );
  }
}
